<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device, initial-scale=1.0">
    <title>用户注册</title>
    <link rel="stylesheet" href="/public/css/login.css">
    <link rel="stylesheet" href="/public/css/common.css">
</head>
<body>
<?php
      include "./common/header.php"
    ?>
   <div class="main">
   <div class="container">
        <h2 style="margin-bottom:10px;text-align:center">用户注册</h2>
        <form action="" id="submit_form" onsubmit="submitForm(event)">
        <ul>
            <li class="line">
                <label for="title">用户名：</label>
                <input type="text" name="username">
            </li>
            <li class="line">
            <label for="title">密 码：</label>
                <input type="password" name="password">
            </li>
            <li class="line">
            <label for="title">确认密码：</label>
                <input type="password" name="re_password"> 
            </li>
            <li class="line submit_line" style="margin-top:30px;margin-left:100px">
                <input type="submit" id="submit" value="提交注册">  
                <a href="./login.php">已有账号?去登录</a>
            </li>
        </ul>  
        </form>
    </div>
   </div>
    <?php
      include "./common/footer.php"
    ?>
    <script>
            //判断输入是否为空
        const isEmpty = (str)=>{
                return str ===undefined || str===null || str.trim() === '';
            }

            // 判断字符串长度
        const strLenMin = (str)=>{
                return str.length<6;
        }
    let pass,re_pass;
    const submitForm = (event)=>{
       event.preventDefault();
      const form =document.getElementById('submit_form');
      const formData = new FormData(form);
      const datas =formData.entries();
      for(const item of datas){
        if(isEmpty(item[1])){
            alert(item[0] + "不能为空")
            break
        }
        if(item[0]==="password"){
            pass = item[1];
        }else{
            re_pass = item[1];
        }

        if(item[0].indexOf('password')>=0){
            if(strLenMin(item[1])){
                alert("密码长度不能小于6")
                return;
            }
        }
      }
      if(pass &&re_pass && pass !==re_pass){
        alert("两次输入密码不一致")
        return;
      }
      let url = "/api/register.php";
        //发送fetch请求
      fetch(url,{
        method:'POST',
        body:formData
      }).then(response=>response.json())
        .then(data=>{
            if(data.code!==0){
                alert(data.msg);
            }else{
                console.log("注册成功")
            }
        }).catch(error=>{
            console.log('error',error)
        })

    }
</script>
</body>

</html>